package cn.txun.springboot31.controller;

import cn.txun.springboot31.entity.Emp;
import cn.txun.springboot31.mapper.EmpMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class EmpController {
    //自动装配：spring扫描到@Autowired时
    //spring会创建EmpMapper的实现类,由Mybatis重写EmpMapper中的所有抽象方法
    //重写的方法中就是原来我们使用JDBC完成的操作
    //最后给这个实现类创建一个对象，让empMapper指向这个对象
    @Autowired
    private EmpMapper empMapper;

    @RequestMapping("/insert")
    @ResponseBody
    public String insert(Emp emp){
        System.out.println("emp = " + emp);
        int rows = empMapper.insert(emp);
        return rows==1?"添加完成!":"添加失败";
    }
    @RequestMapping("/select")
    @ResponseBody
    public String select(){
        List<Emp> list = empMapper.select();
        String html = "<table border='1' >";
        html+="<tr><th>id</th><th>姓名</th><th>职位</th><th>工资</th><th>操作</th></tr>";
        for(Emp e:list){
            html+="<tr>";
            html+="<td>"+e.getId()+"</td>";
            html+="<td>"+e.getName()+"</td>";
            html+="<td>"+e.getJob()+"</td>";
            html+="<td>"+e.getSal()+"</td>";
            html+="<td><a href='/delete?id="+e.getId()+"'>删除</a></td>";
            html+="</tr>";
        }
        html+="</table>";
        return html;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(int id){
        System.out.println("id = " + id);
        empMapper.deleteById(id);
        return "删除成功，返回<a href='/select'>员工列表</a>";
    }
    @RequestMapping("/update")
    @ResponseBody
    public String update(Emp emp){
        System.out.println("emp = " + emp);
        empMapper.update(emp);
        return "修改成功，返回<a href='/select'>员工列表</a>";
    }
}
